package com.siteseat.common.misc;

import java.io.File;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

/**
 *
 */
public class Shutdownable {
  
  private String homeVariableName;
  
  private String shutdownSignalFileName;
  
  private long shutdownCheckInterval;
  
  public Shutdownable() {
    setHomeVariableName( "HOME" );    
    setShutdownSignalFileName( "pleaseshutdown" );
    setShutdownCheckInterval( 4 * 1000 );
  }
  
  /**
   * Sets the homeVariableName
   *
   * @param homeVariableName the homeVariableName to set
   */
  public void setHomeVariableName( String homeVariableName ) {
    this.homeVariableName = homeVariableName;
  }

  public String getHomeVariableName() {
    return homeVariableName;
  }

  /**
   * 
   *
   * @return
   */
  protected String determineHome() {
    String homeVarName = getHomeVariableName();
    String home = System.getProperty( homeVarName );
    if( StringUtils.isBlank( home ) ) {
      System.err.println( "Please set environ variable " + homeVarName );
      return null;
    }
    
    return home;
  }
  

  /**
   * 
   *
   * @return
   */
  protected String determineShutdownSignalFilePath() {
    return determineHome() + File.separator + getShutdownSignalFileName();
  }
  
  public String getShutdownSignalFileName() {
    return shutdownSignalFileName;
  }
  
  /**
   * Sets the shutdownSignalFileName
   *
   * @param shutdownSignalFileName the shutdownSignalFileName to set
   */
  public void setShutdownSignalFileName( String shutdownSignalFileName ) {
    this.shutdownSignalFileName = shutdownSignalFileName;
  }

  /**
   * 
   *
   * @return
   * @throws IOException 
   */
  protected File resolveShutdownSignalFile() throws IOException {
    File r = new File( determineShutdownSignalFilePath() );
    if( r.exists() ) {
      r.delete();
    }
    if( r.createNewFile() == false ) {
      System.err.println( "Cannot create signal file: " + r );
      return null;
    } 

    return r;
  }
  
  /**
   * @return
   */
  public long getShutdownCheckInterval() {
    return shutdownCheckInterval;
  }
  
  /**
   * Sets the shutdownCheckInterval
   *
   * @param shutdownCheckInterval the shutdownCheckInterval to set
   */
  public void setShutdownCheckInterval( long shutdownCheckInterval ) {
    this.shutdownCheckInterval = shutdownCheckInterval;
  }

}
